package myTeam.timeShop.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.management.RuntimeErrorException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

import myTeam.timeShop.bean.TbComment;
import myTeam.timeShop.bean.TbDemand;
import myTeam.timeShop.bean.TbLike;
import myTeam.timeShop.bean.TbRequest;
import myTeam.timeShop.bean.TbUser;
import myTeam.timeShop.dao.DemandDao;
import myTeam.timeShop.dao.UserDao;
import myTeam.timeShop.entity.Comment;
import myTeam.timeShop.entity.Demand;
import myTeam.timeShop.entity.User;
import myTeam.timeShop.service.DemandService;
import myTeam.timeShop.service.RequestService;
import myTeam.timeShop.service.UserService;
@Service("demandService")
public class DemandServiceImpl implements DemandService {
	@Autowired
	RequestService requestService;
	@Autowired
	DemandDao demandDao;
	@Autowired
	UserDao userDao;
	@Override
	public TbDemand load(String id) {

		return this.demandDao.load(id);
	}

	@Override
	public TbDemand get(String id) {

		return this.demandDao.get(id);
	}

	@Override
	public List<TbDemand> findAll() {

		return this.demandDao.findAll();
	}

	@Override
	public void persist(TbDemand entity) {

		this.demandDao.persist(entity);
	}

	@Override
	public String save(TbDemand entity) {

		return this.demandDao.save(entity).toString();
	}

	@Override
	public void saveOrUpdate(TbDemand entity) {

		this.demandDao.saveOrUpdate(entity);
	}

	@Override
	public void delete(String id) {

		this.demandDao.delete(id);
	}

	@Override
	public void flush() {

		this.demandDao.flush();
	}

	/* （非 Javadoc）
	 * @see myTeam.timeShop.service.DemandService#getUserDemand(java.lang.String, java.lang.String)
	 */
	@Override
	
	public List<TbDemand> getUserDemand(String pageNo, String size,String userId) {

			List<TbDemand> list= this.demandDao.getUserDemand(pageNo, size,userId);
			List<TbDemand> demandList = new ArrayList<TbDemand>();
			
			for(int i=0;i<list.size();i++){
				Demand d = new Demand();
				d.setDemandAcceptTime(list.get(i).getDemandAcceptTime());
				d.setDemandCancelTime(list.get(i).getDemandCancelTime());
				if(list.get(i).getTbUserByDemandClientId()!=null) d.setDemandClientId(list.get(i).getTbUserByDemandClientId().getUserId());
				d.setDemandCommentCount(list.get(i).getDemandCommentCount());
				d.setDemandContent(list.get(i).getDemandContent());
				d.setDemandFinishTime(list.get(i).getDemandFinishTime());
				d.setDemandId(list.get(i).getDemandId());
				d.setDemandLikeCount(list.get(i).getDemandLikeCount());
				d.setDemandPay(list.get(i).getDemandPay());
				d.setDemandPhotoUrlJson(list.get(i).getDemandPhotoUrlJson());
				d.setDemandStatus(list.get(i).getDemandStatus());
				d.setDemandTime(list.get(i).getDemandTime());
				d.setDemandTitle(list.get(i).getDemandTitle());
				d.setDemandType(list.get(i).getDemandType());
				d.setDemandUserId(list.get(i).getTbUserByDemandUserId().getUserId());
				Set<TbLike> likeList =  list.get(i).getTbLikes();
				for(Iterator<TbLike> index = likeList.iterator();index.hasNext();){
					TbLike like = index.next();
					if(like.getTbUser().getUserId().equals(d.getDemandUserId())&&like.getLikeDeleteStatus()!=1){
						d.setDemandSaidLike(1);
					}else{
						d.setDemandSaidLike(0);
					}
				}
				
				demandList.add(d);
				
				
				
			}
			return demandList;
	}

	/* （非 Javadoc）
	 * @see myTeam.timeShop.service.DemandService#getUserRequestDemand(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	
	public List<TbDemand> getUserRequestDemand(String pageNo, String size,
			String filterUserId) {
		List<TbDemand> list = demandDao.getUserRequestDemand(pageNo,size,filterUserId);
		List<TbDemand> demandList = new ArrayList<TbDemand>();
		for(int i=0;i<list.size();i++){
			Demand d = new Demand();
			d.setDemandAcceptTime(list.get(i).getDemandAcceptTime());
			d.setDemandCancelTime(list.get(i).getDemandCancelTime());
			if(list.get(i).getTbUserByDemandClientId()!=null) d.setDemandClientId(list.get(i).getTbUserByDemandClientId().getUserId());
			d.setDemandCommentCount(list.get(i).getDemandCommentCount());
			d.setDemandContent(list.get(i).getDemandContent());
			d.setDemandFinishTime(list.get(i).getDemandFinishTime());
			d.setDemandId(list.get(i).getDemandId());
			d.setDemandLikeCount(list.get(i).getDemandLikeCount());
			d.setDemandPay(list.get(i).getDemandPay());
			d.setDemandPhotoUrlJson(list.get(i).getDemandPhotoUrlJson());
			d.setDemandStatus(list.get(i).getDemandStatus());
			d.setDemandTime(list.get(i).getDemandTime());
			d.setDemandTitle(list.get(i).getDemandTitle());
			d.setDemandType(list.get(i).getDemandType());
			d.setDemandUserId(list.get(i).getTbUserByDemandUserId().getUserId());
			Set<TbLike> likeList =  list.get(i).getTbLikes();
			for(Iterator<TbLike> index = likeList.iterator();index.hasNext();){
				TbLike like = index.next();
				if(like.getTbUser().getUserId().equals(d.getDemandUserId())&&like.getLikeDeleteStatus()!=1){
					d.setDemandSaidLike(1);
				}else{
					d.setDemandSaidLike(0);
				}
			}
			demandList.add(d);
		}
		return demandList;
	}

	/* （非 Javadoc）
	 * @see myTeam.timeShop.service.DemandService#getAllDemand(java.lang.String, java.lang.String)
	 */
	@Override
	
	public List<TbDemand> getAllDemand(String pageNo, String size,String filterUserId) {

		List<TbDemand> list = demandDao.getAllDemand(pageNo, size) ;
		List<TbDemand> demandList = new ArrayList<TbDemand>();
		for(int i=0;i<list.size();i++){
			Demand d = new Demand();
			//封装用户体
			User user = new User();
			user.setUserAccount(list.get(i).getTbUserByDemandUserId().getUserAccount());
			user.setUserFacePath(list.get(i).getTbUserByDemandUserId().getUserFacePath());
			user.setUserId(list.get(i).getTbUserByDemandUserId().getUserId());
			user.setUserLevel(list.get(i).getTbUserByDemandUserId().getUserLevel());
			user.setUserName(list.get(i).getTbUserByDemandUserId().getUserName());
			user.setUserSchool(list.get(i).getTbUserByDemandUserId().getUserSchool());
			user.setUserSex(list.get(i).getTbUserByDemandUserId().getUserSex());
			
			d.setTbUserByDemandUserId(user);
			d.setDemandAcceptTime(list.get(i).getDemandAcceptTime());
			d.setDemandCancelTime(list.get(i).getDemandCancelTime());
			if(list.get(i).getTbUserByDemandClientId()!=null) d.setDemandClientId(list.get(i).getTbUserByDemandClientId().getUserId());
			d.setDemandCommentCount(list.get(i).getDemandCommentCount());
			d.setDemandContent(list.get(i).getDemandContent());
			d.setDemandFinishTime(list.get(i).getDemandFinishTime());
			d.setDemandId(list.get(i).getDemandId());
			d.setDemandLikeCount(list.get(i).getDemandLikeCount());
			d.setDemandPay(list.get(i).getDemandPay());
			d.setDemandPhotoUrlJson(list.get(i).getDemandPhotoUrlJson());
			d.setDemandStatus(list.get(i).getDemandStatus());
			d.setDemandTime(list.get(i).getDemandTime());
			d.setDemandTitle(list.get(i).getDemandTitle());
			d.setDemandType(list.get(i).getDemandType());
			d.setDemandUserId(list.get(i).getTbUserByDemandUserId().getUserId());
			Set<TbLike> likeList =  list.get(i).getTbLikes();
			for(Iterator<TbLike> index = likeList.iterator();index.hasNext();){
				TbLike like = index.next();
				if(like.getTbUser().getUserId().equals(filterUserId)&&like.getLikeDeleteStatus()!=1){
					d.setDemandSaidLike(1);
				}else{
					d.setDemandSaidLike(0);
				}
			}
			demandList.add(d);

		}
		return demandList;
	}

	/* （非 Javadoc）
	 * @see myTeam.timeShop.service.DemandService#getMySchoolDemand(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	
	public List<TbDemand> getMySchoolDemand(String userSchool, String pageNo,
			String size,String filterUserId) {
		List<TbDemand> list = this.demandDao.getMySchoolDemand(userSchool, pageNo,size);
		List<TbDemand> demandList = new ArrayList<TbDemand>();
		
		for(int i=0;i<list.size();i++){
			Demand d = new Demand();
			//封装用户体
			User user = new User();
			user.setUserAccount(list.get(i).getTbUserByDemandUserId().getUserAccount());
			user.setUserFacePath(list.get(i).getTbUserByDemandUserId().getUserFacePath());
			user.setUserId(list.get(i).getTbUserByDemandUserId().getUserId());
			user.setUserLevel(list.get(i).getTbUserByDemandUserId().getUserLevel());
			user.setUserName(list.get(i).getTbUserByDemandUserId().getUserName());
			user.setUserSchool(list.get(i).getTbUserByDemandUserId().getUserSchool());
			user.setUserSex(list.get(i).getTbUserByDemandUserId().getUserSex());
			
			d.setTbUserByDemandUserId(user);
			d.setDemandAcceptTime(list.get(i).getDemandAcceptTime());
			d.setDemandCancelTime(list.get(i).getDemandCancelTime());
			if(list.get(i).getTbUserByDemandClientId()!=null) d.setDemandClientId(list.get(i).getTbUserByDemandClientId().getUserId());
			d.setDemandCommentCount(list.get(i).getDemandCommentCount());
			d.setDemandContent(list.get(i).getDemandContent());
			d.setDemandFinishTime(list.get(i).getDemandFinishTime());
			d.setDemandId(list.get(i).getDemandId());
			d.setDemandLikeCount(list.get(i).getDemandLikeCount());
			d.setDemandPay(list.get(i).getDemandPay());
			d.setDemandPhotoUrlJson(list.get(i).getDemandPhotoUrlJson());
			d.setDemandStatus(list.get(i).getDemandStatus());
			d.setDemandTime(list.get(i).getDemandTime());
			d.setDemandTitle(list.get(i).getDemandTitle());
			d.setDemandType(list.get(i).getDemandType());
			d.setDemandUserId(list.get(i).getTbUserByDemandUserId().getUserId());
			Set<TbLike> likeList =  list.get(i).getTbLikes();
			for(Iterator<TbLike> index = likeList.iterator();index.hasNext();){
				TbLike like = index.next();
				if(like.getTbUser().getUserId().equals(filterUserId)&&like.getLikeDeleteStatus()!=1){
					d.setDemandSaidLike(1);
				}else{
					d.setDemandSaidLike(0);
				}
			}
			demandList.add(d);

		}
		return demandList;
	}

	/* （非 Javadoc）
	 * @see myTeam.timeShop.service.DemandService#getDemandDetail(java.lang.String)
	 */
	@Override
	
	public TbDemand getDemandDetail(String demandId,String filterUserId) {
		TbDemand demand  = this.get(demandId);
		Demand clientDemand  = new Demand();
		//实例化发帖用户
		User user = new User();
		user.setUserAccount(demand.getTbUserByDemandUserId().getUserAccount());
		user.setUserFacePath(demand.getTbUserByDemandUserId().getUserFacePath());
		user.setUserId(demand.getTbUserByDemandUserId().getUserId());
		user.setUserLevel(demand.getTbUserByDemandUserId().getUserLevel());
		user.setUserName(demand.getTbUserByDemandUserId().getUserName());
		user.setUserSchool(demand.getTbUserByDemandUserId().getUserSchool());
		user.setUserSex(demand.getTbUserByDemandUserId().getUserSex());
		
		//实例化帖子内容
		clientDemand.setTbUserByDemandUserId(user);
		clientDemand.setDemandId(demand.getDemandId());
		clientDemand.setDemandContent(demand.getDemandContent());
		clientDemand.setDemandType(demand.getDemandType());
		clientDemand.setDemandPay(demand.getDemandPay());
		clientDemand.setDemandPhotoUrlJson(demand.getDemandPhotoUrlJson());
		clientDemand.setDemandLikeCount(demand.getDemandLikeCount());
		clientDemand.setDemandTitle(demand.getDemandTitle());
		clientDemand.setDemandTime(demand.getDemandTime());
		clientDemand.setDemandCommentCount(demand.getDemandCommentCount());
		clientDemand.setDemandStatus(demand.getDemandStatus());
		Set<TbLike> likeList =  demand.getTbLikes();
		for(Iterator<TbLike> index = likeList.iterator();index.hasNext();){
			TbLike like = index.next();
			if(like.getTbUser().getUserId().equals(filterUserId)&&like.getLikeDeleteStatus()!=1){
				clientDemand.setDemandSaidLike(1);
			}else{
				clientDemand.setDemandSaidLike(0);
			}
		}
		
		
		//构造评论表
		Set<TbComment> tbCommentList = demand.getTbComments();
		Set<TbComment> commentList = new HashSet<>();
		for(Iterator<TbComment> i=tbCommentList.iterator();i.hasNext();){
			Comment comment = new Comment();
			
			TbComment tbComment = i.next();
			
			//构造评论用户
			User commentUser = new User();
			commentUser.setUserAccount(tbComment.getTbUser().getUserAccount());
			commentUser.setUserFacePath(tbComment.getTbUser().getUserFacePath());
			commentUser.setUserId(tbComment.getTbUser().getUserId());
			commentUser.setUserLevel(tbComment.getTbUser().getUserLevel());
			commentUser.setUserName(tbComment.getTbUser().getUserName());
			commentUser.setUserSchool(tbComment.getTbUser().getUserSchool());
			commentUser.setUserSex(tbComment.getTbUser().getUserSex());
			comment.setTbUser(commentUser);
			//构造评论内容
			comment.setCommentContent(tbComment.getCommentContent());
			comment.setCommentDemandId(tbComment.getCommentId());
			comment.setCommentId(tbComment.getCommentId());
			comment.setCommentIsSaw(tbComment.getCommentIsSaw());
			comment.setCommentTime(tbComment.getCommentTime());
			comment.setCommentUserId(tbComment.getTbUser().getUserId());
			comment.setParentId(tbComment.getTbComment()!=null?tbComment.getTbComment().getCommentId():-1);
			//添加到评论列表
			commentList.add(comment);
		}
		clientDemand.setTbComments(commentList);
		
		return  clientDemand;
	}

	/* （非 Javadoc）
	 * @see myTeam.timeShop.service.DemandService#doTheLikeOrNot(java.lang.String, java.lang.String)
	 */
	@Override
	
	public void doTheLikeOrNot(String demandId, String type,String filterUserId) {
		if(type.equals("1")){//表示点赞
			TbDemand tbDemand = this.get(demandId);//获取需求表
			TbUser user = userDao.get(filterUserId);
			Set<TbLike> likeSet = tbDemand.getTbLikes();//获取点赞表
			
			int count = 0;//记录用户是否点赞过
			for(Iterator<TbLike> i = likeSet.iterator();i.hasNext();  ) {
				TbLike  like = i.next();//获取点赞表
				//判断用户是否点赞过
				if(like.getTbUser().getUserId().equals(filterUserId)){//表示曾经点赞过
					count= count+1;
					if(like.getLikeDeleteStatus().equals(1)){//表示是否被删除，是才修改
						tbDemand.setDemandLikeCount(tbDemand.getDemandLikeCount()+1);//点赞数加一
						like.setLikeDeleteStatus(0);
					}
				}
			}
			if(count == 0){//表示用户未曾点过赞
				TbLike  like = new TbLike();
				like.setLikeDeleteStatus(0);
				like.setLikeIsSaw(0);
				like.setLikeTime(new Date());
				like.setTbDemand(tbDemand);
				like.setTbUser(user);
				likeSet.add(like);//添加进集合
				tbDemand.setDemandLikeCount(tbDemand.getDemandLikeCount()+1);//点赞数加一
			}
			tbDemand.setTbLikes(likeSet);//更新like表

			this.saveOrUpdate(tbDemand);//更新全部
		}else{//表示取消赞
			TbDemand tbDemand = this.get(demandId);//获取需求表
			Set<TbLike> likeSet = tbDemand.getTbLikes();//获取点赞表
			
			int count = 0;//记录用户是否点赞过
			for(Iterator<TbLike> i = likeSet.iterator();i.hasNext();  ) {
				TbLike  like = i.next();//获取点赞表
				//判断用户是否点赞过
				if(like.getTbUser().getUserId().equals(filterUserId)){//表示曾经点赞过
					count= count+1;
					if(!like.getLikeDeleteStatus().equals(1)){//表示是否被删除，否才修改
						like.setLikeDeleteStatus(1);
						tbDemand.setDemandLikeCount(tbDemand.getDemandLikeCount()-1);//点赞数加一
					}
				}
			}
			if(count == 0){//表示用户未曾点过赞
				//不做处理
			}
			tbDemand.setTbLikes(likeSet);//更新like表
			this.saveOrUpdate(tbDemand);//更新全部
		}
		
	}

	/* （非 Javadoc）
	 * @see myTeam.timeShop.service.DemandService#addComment(java.lang.String, java.lang.String)
	 */
	@Override
	
	public void addComment(String demandId, String content,String filterUserId) {
		TbDemand tbDemand = this.get(demandId);
		TbUser tbUser = userDao.get(filterUserId);
		TbComment tbComment = new TbComment();
		tbComment.setCommentContent(content);
		tbComment.setCommentIsSaw(0);
		tbComment.setCommentTime(new Date());
		tbComment.setTbComment(null);
		tbComment.setTbDemand(tbDemand);
		tbComment.setTbUser(tbUser);
		
		tbDemand.getTbComments().add(tbComment);//添加评论
		tbDemand.setDemandCommentCount(tbDemand.getDemandCommentCount()+1);//添加评论数
		demandDao.saveOrUpdate(tbDemand);//保存
		
		
	}

	/* （非 Javadoc）
	 * @see myTeam.timeShop.service.DemandService#addDemandRequest(java.lang.String, java.lang.String)
	 */
	@Override
	
	public void addDemandRequest(String demandId, String filterUserId,String message) throws Exception {
		TbDemand tbDemand = this.get(demandId);
		TbUser tbUser = userDao.get(filterUserId);
		Set<TbRequest> set= tbDemand.getTbRequests();
		
		if(tbDemand.getDemandStatus()!=0){
			throw new Exception("该订单已经被抢了，下次快点吧");
		}
		for(Iterator<TbRequest> i = set.iterator();i.hasNext(); ) {
			TbRequest tbRequest = i.next();
			if(tbRequest.getTbUser().getUserId().equals(filterUserId)){
				throw new Exception("您已经请求过了，请耐心等候吧");
			}
		}
		
		TbRequest request = new TbRequest();
		request.setRequestMessage(message);
		request.setRequestStatus(0);
		request.setRequestTime(new Date());
		request.setTbDemand(tbDemand);
		request.setTbUser(tbUser);
		
		requestService.save(request);
		
	}

}
